import path from 'path'
import fs from 'fs'
import Router from 'koa-router'
import Koa from 'koa'
import body from 'koa-body'
import json from 'koa-json'
import globalException from './GlobalExce'

export class AllRouterLoader {
  app!: Koa
  static allRouterLoader: AllRouterLoader = new AllRouterLoader()
  init(app: Koa) {
    this.app = app
    // const p = this.getAbsoluteFilePath()
    // console.log('getAbsoluteFilePath', p)
    const rootRouter = this.loadAllRouterWrapper()
    this.app.use(globalException)
    this.app.use(rootRouter.routes())
    this.listen()
  }

  //1、加载所有路由文件数组
  getFiles(dir: string) {
    const allFiles = fs.readdirSync(dir)
    // console.log('all files:', allFiles)
    return allFiles
  }
  //2、加载所有路由文件绝对路径数组
  getAbsoluteFilePath(): string[] {
    const dir = path.join(process.cwd(), '/src/router')
    const allFiles = this.getFiles(dir)
    const allFullFilePaths: string[] = []
    for (const file of allFiles) {
      const fullFilePath = dir + '/' + file
      allFullFilePaths.push(fullFilePath)
    }
    return allFullFilePaths
  }
  //3、加载所有一级路由到二级路由中
  loadAllRouterWrapper() {
    //3.0 获取一级路由
    const rootRouter = this.getRootRouter()
    //3.1 调用获取绝对路径数组方法
    const allFullFilePaths = this.getAbsoluteFilePath()
    //3.2 调用加载所有一级路由到二级路由方法

    this.loadAllRouter(allFullFilePaths, rootRouter)

    return rootRouter
  }

  getRootRouter() {
    const rootRouter = new Router()
    rootRouter.prefix('/dang') //为所有路由访问添加路由前缀/dang，作为一级路由
    rootRouter.use(json())
    rootRouter.use(body())
    return rootRouter
  }

  loadAllRouter(allFullFilePaths: string[], rootRouter: Router) {
    console.log('111', allFullFilePaths)
    for (const fullFilePath of allFullFilePaths) {
      const routerWrapper = require(fullFilePath)
      if (this.isRouter(routerWrapper)) {
        rootRouter.use(routerWrapper.routes(), routerWrapper.allowedMethods())
      }
      // const router = routerWrapper.default
      // console.log('routerWrapper', routerWrapper)
      // console.log('router', router)
      //3.3 调用加载所有一级路由到二级路由方法
      // this.loadRouter(router)
    }
  }
  //自定义守卫
  isRouter(data: any): data is Router {
    return data instanceof Router
  }
  listen() {
    this.app.listen(3002)
    console.log('server is running on port 3002')
  }
}

export default AllRouterLoader.allRouterLoader
